const express = require("express");
const { createServer } = require("http");
const { Server } = require("socket.io");
const { writeFileSync } = require("fs");

const app = express();
app.use("/upload", express.static('upload'))
const httpServer = createServer(app);
const io = new Server(httpServer, {
  cors: {
    origin: "*",
    allowedHeaders: "*",
    credentials: true
  }
});
//后端
//存取所有 Socket
let onlineUserSocket = []
//在线群人员
let onlineUserList = {
}

//消息
let ChatRecords = {
  "10086": [
    {
      room_id: "10086",
      user_img: "../img/7.jpg",
      user_name: "bmy",
      level: 1,//1群主  2 管理员 3 普通成员
      message: '这是我发的消息'
    }
  ]
}
//链接是否成功
io.on("connection", (socket) => {
  console.log("链接成")
  //存取socket

  socket.on('socketShake', (msg) => {
    console.log("msg", msg)

    if (msg.hasOwnProperty("clickUserName")) {
      //私发消息
      let userSocket = onlineUserSocket.filter(v => onlineUserList[msg.room_id].filter(v => msg.clickUserName == v.user_name)[0].socketId == v.id)[0];

      let a = parseInt(Math.random() * 100000)
      console.log("a: ", a);

      socket.join(a);
      userSocket.join(a)


      io.in(a).emit("ShakeMessage", msg)
      io.in(a).emit("openShake")
    } else {
      //群发
      //群发消息
      io.in(msg.room_id).emit("ShakeMessage", msg)
      io.in(msg.room_id).emit("openShake");
    }



  })

  socket.on("Mushinsocket", (msg) => {
    //禁言判断
    console.log("msg", msg)
    if (msg.hasOwnProperty("Mushinname")) {
      //判断操作之人的等级
      let grade = onlineUserList[msg.room_id].filter(v => v.user_name == msg.user_name)[0]
      if (grade.level == 1) {
        let a = parseInt(Math.random() * 100000)
        gradesocket = onlineUserSocket.filter(v => v.id == onlineUserList[msg.room_id].filter(v => v.user_name == msg.Mushinname)[0].socketId)[0]
        gradesocket.join(a)
        io.in(a).emit("MushinopenShake")
        io.in(msg.room_id).emit("WelcomeUser", `用户${msg.Mushinname}已被禁言`);
      }
    }
  })
  socket.on("Allsilenced", (msg) => {
    let grade = onlineUserList[msg.room_id].filter(v => v.user_name == msg.user_name)[0]
    if(grade.level==1){
      socket.to(msg.room_id).emit("MushinsocketAll");
      io.in(msg.room_id).emit("WelcomeUser", `群主开启了全员禁言`);
    }
  })
  socket.on('uploadFile', (msg) => {
    console.log("图片base64: ", msg);
    msg.user.message = saveFile(msg)
    socket.to(msg.user.room_id).emit("uploadImgName", msg.user);
  })

  //加入群聊
  socket.on('text', (msg) => {
    console.log('message: ', msg);
    //hasOwnProperty
    //判断是否存在此群
    if (onlineUserList.hasOwnProperty(msg.room_id)) {
      console.log("存在此群")

      //判断群里是否有此人
      console.log(checkUserNameisExist(msg))
      if (checkUserNameisExist(msg)) {
        console.log("群里没有此人")
        //没有此人
        msg.level = 3 //为成员
        //
        msg.socketId = socket.id
        onlineUserList[msg.room_id].push(msg)
      }
      onlineUserSocket.push(socket)
      socket.join(msg.room_id);
    } else {
      //不存在群
      console.log("不存在此群")
      onlineUserList[msg.room_id] = []
      msg.level = 1
      msg.socketId = socket.id
      onlineUserList[msg.room_id].push(msg)
      onlineUserSocket.push(socket)
      console.log("不存在此群", onlineUserList);
      socket.join(msg.room_id);

    }

    io.in(msg.room_id).emit("WelcomeUser", `欢迎用户${msg.user_name}加入群聊`);
    //向前端发送群成员信息
    io.in(msg.room_id).emit("onLineUserList", onlineUserList[msg.room_id]);
    console.log("所有", onlineUserList)
  });
  //接受前端发来的消息数据
  socket.on("sendMessage", data => {
    //将消息发送给指前端除自己以外房间里的所有人
    console.log("收到的前端消息", data)
    socket.to(data.room_id).emit("ServerMessage", data)
  })

});

function checkUserNameisExist(msg) {
  let ddd = onlineUserList[msg.room_id].filter(v => {
    //将相等的数据返回
    return v.user_name == msg.user_name
  })

  return ddd == 0 ? true : false;
}

function saveFile(imgData) {
  var base64Data = imgData.base64.replace(/^data:image\/\w+;base64,/, "");
  var dataBuffer = Buffer.from(base64Data, 'base64');
  let fileName = `${new Date().getTime().toString() + (Math.random() * new Date().getTime())}.${imgData.fileType}`
  writeFileSync(`upload/${fileName}`, dataBuffer);
  return fileName
}

httpServer.listen(3000, () => {
  console.log("ws://127.0.0.1:3000")
});


